{% extends "base.html" %}

{% block title %}摄像头车牌识别 - 车辆管理系统{% endblock %}

{% block content %}
<div class="container">
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="text-center">摄像头车牌识别</h2>
            <p class="text-center text-muted">使用摄像头实时识别车牌，自动进入停车场</p>
        </div>
    </div>

    <div class="row">
        <div class="col-md-8 offset-md-2">
            <!-- 停车场选择 -->
            <div class="card mb-4">
                <div class="card-header">停车场信息</div>
                <div class="card-body">
                    <form id="enterParkingForm" action="{{ url_for('enter_with_camera') }}" method="post">
                        <div class="mb-3">
                            <label for="parking_lot_id" class="form-label">选择停车场</label>
                            <select class="form-select" id="parking_lot_id" name="parking_lot_id" required>
                                <option value="" selected disabled>请选择停车场</option>
                                {% for lot in parking_lots %}
                                    <option value="{{ lot.id }}" 
                                        data-spaces="{{ lot.total_spaces - (lot.total_spaces - lot.available_spaces) }}" 
                                        data-total="{{ lot.total_spaces }}"
                                        data-rate="{{ lot.hourly_rate }}"
                                        {% if lot.available_spaces <= 0 %}disabled{% endif %}>
                                        {{ lot.name }} (¥{{ lot.hourly_rate }}/小时) - 
                                        {% if lot.available_spaces > 0 %}
                                            剩余{{ lot.available_spaces }}个车位
                                        {% else %}
                                            已满
                                        {% endif %}
                                    </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div id="parking-info" class="form-text mt-2 mb-3 d-none">
                            <div class="card">
                                <div class="card-body py-2">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <strong>可用车位:</strong> <span id="available-spaces">-</span>/<span id="total-spaces">-</span>
                                        </div>
                                        <div class="col-md-6">
                                            <strong>费率:</strong> ¥<span id="hourly-rate">-</span>/小时
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" id="detected_plate" name="detected_plate" value="">
                    </form>
                </div>
            </div>
            
            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <span>实时摄像头</span>
                        <div>
                            <button id="startCameraBtn" class="btn btn-primary btn-sm">启动摄像头</button>
                            <button id="stopCameraBtn" class="btn btn-danger btn-sm" style="display:none;">停止摄像头</button>
                            <a href="{{ url_for('user_dashboard') }}" class="btn btn-secondary btn-sm">返回仪表盘</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div id="parkingLotAlert" class="alert alert-warning text-center my-2" style="display:none;">
                        请先选择停车场，再启动摄像头！
                    </div>
                    
                    <div class="text-center">
                        <!-- 摄像头流展示区域 -->
                        <img id="cameraFeed" src="{{ url_for('video_feed') }}" style="max-width:100%; height:auto; display:none;" class="border">
                    </div>
                    
                    <div id="loadingIndicator" style="display:none;" class="text-center my-3">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="text-muted mt-2">正在加载摄像头和识别模型，请稍候...</p>
                    </div>
                    
                    <div id="detectionResult" class="alert alert-info text-center mt-3" style="display:none;">
                        正在识别中，请将车牌对准摄像头...
                    </div>
                    
                    <div id="successResult" class="alert alert-success text-center mt-3" style="display:none;">
                        <strong style="font-size: 1.2em;">识别成功!</strong> 
                        <div style="font-size: 1.3em; margin: 10px 0;">
                            车牌号: <span id="plateNumber" style="font-weight: bold;"></span>
                        </div>
                        <div class="mt-2">
                            <p style="font-size: 1.2em; color: #155724; font-weight: bold;">
                                <span id="countdown">5</span> 秒后自动返回用户中心...
                            </p>
                        </div>
                    </div>
                    
                    <div id="timeoutResult" class="alert alert-warning text-center mt-3" style="display:none;">
                        <strong>超时!</strong> 未能在规定时间内识别到车牌
                        <div class="mt-2">
                            <p>系统将在 <span id="timeoutCountdown">5</span> 秒后自动返回...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const startCameraBtn = document.getElementById('startCameraBtn');
        const stopCameraBtn = document.getElementById('stopCameraBtn');
        const cameraFeed = document.getElementById('cameraFeed');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const detectionResult = document.getElementById('detectionResult');
        const successResult = document.getElementById('successResult');
        const timeoutResult = document.getElementById('timeoutResult');
        const plateNumber = document.getElementById('plateNumber');
        const countdown = document.getElementById('countdown');
        const timeoutCountdown = document.getElementById('timeoutCountdown');
        const detectedPlateInput = document.getElementById('detected_plate');
        const parkingLotSelect = document.getElementById('parking_lot_id');
        const enterParkingForm = document.getElementById('enterParkingForm');
        const parkingLotAlert = document.getElementById('parkingLotAlert');
        
        let recognitionInterval;
        let countdownTimer;
        let timeoutCountdownTimer;
        
        // 显示选择的停车场信息
        parkingLotSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const parkingInfo = document.getElementById('parking-info');
            const availableSpaces = document.getElementById('available-spaces');
            const totalSpaces = document.getElementById('total-spaces');
            const hourlyRate = document.getElementById('hourly-rate');
            
            if (selectedOption.value) {
                availableSpaces.textContent = selectedOption.dataset.spaces;
                totalSpaces.textContent = selectedOption.dataset.total;
                hourlyRate.textContent = selectedOption.dataset.rate;
                parkingInfo.classList.remove('d-none');
            } else {
                parkingInfo.classList.add('d-none');
            }
        });
        
        // 开始摄像头
        startCameraBtn.addEventListener('click', function() {
            // 检查是否选择了停车场
            if (!parkingLotSelect.value) {
                parkingLotAlert.style.display = 'block';
                setTimeout(() => {
                    parkingLotAlert.style.display = 'none';
                }, 3000);
                return;
            }
            
            startCameraBtn.disabled = true;
            loadingIndicator.style.display = 'block';
            
            // 向服务器发送请求启动摄像头
            fetch('{{ url_for("start_camera") }}')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 显示摄像头流
                        cameraFeed.style.display = 'block';
                        stopCameraBtn.style.display = 'inline-block';
                        startCameraBtn.style.display = 'none';
                        loadingIndicator.style.display = 'none';
                        detectionResult.style.display = 'block';
                        
                        // 开始每秒检查识别结果
                        recognitionInterval = setInterval(checkRecognitionResult, 1000);
                        
                        // 设置超时检测 - 30秒后如果没有识别到车牌，则显示超时
                        setTimeout(function() {
                            if (!detectedPlateInput.value && detectionResult.style.display !== 'none') {
                                clearInterval(recognitionInterval);
                                detectionResult.style.display = 'none';
                                timeoutResult.style.display = 'block';
                                startTimeoutCountdown();
                            }
                        }, 30000);
                    } else {
                        alert('启动摄像头失败：' + data.message);
                        startCameraBtn.disabled = false;
                        loadingIndicator.style.display = 'none';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('启动摄像头时发生错误');
                    startCameraBtn.disabled = false;
                    loadingIndicator.style.display = 'none';
                });
        });
        
        // 停止摄像头
        stopCameraBtn.addEventListener('click', function() {
            stopCamera();
        });
        
        // 检查识别结果
        function checkRecognitionResult() {
            fetch('{{ url_for("check_recognition") }}')
                .then(response => response.json())
                .then(data => {
                    if (data.plate) {
                        // 识别成功
                        clearInterval(recognitionInterval);
                        
                        // 停止摄像头视频流但保留最后一帧
                        cameraFeed.style.opacity = '0.6';
                        
                        // 隐藏识别中提示，显示成功提示
                        detectionResult.style.display = 'none';
                        successResult.style.display = 'block';
                        
                        // 设置车牌号
                        plateNumber.textContent = data.plate;
                        detectedPlateInput.value = data.plate;
                        
                        // 在控制台显示日志（调试用）
                        console.log('检测到车牌: ' + data.plate + '，开始倒计时');
                        
                        // 直接开始5秒倒计时并自动提交
                        startQuickCountdown();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
        
        // 停止摄像头
        function stopCamera() {
            fetch('{{ url_for("stop_camera") }}')
                .then(response => response.json())
                .then(data => {
                    cameraFeed.style.display = 'none';
                    stopCameraBtn.style.display = 'none';
                    startCameraBtn.style.display = 'inline-block';
                    startCameraBtn.disabled = false;
                    detectionResult.style.display = 'none';
                    
                    clearInterval(recognitionInterval);
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
        
        // 快速5秒倒计时并提交
        function startQuickCountdown() {
            let seconds = 5;
            countdown.textContent = seconds;
            
            // 确保倒计时区域可见
            successResult.style.display = 'block';
            
            // 添加CSS动画效果
            countdown.style.transition = 'all 0.5s';
            countdown.style.fontSize = '1.5em';
            
            countdownTimer = setInterval(function() {
                seconds--;
                countdown.textContent = seconds;
                
                // 当倒计时接近结束时改变颜色
                if (seconds <= 2) {
                    countdown.style.color = '#dc3545';
                }
                
                if (seconds <= 0) {
                    clearInterval(countdownTimer);
                    enterParkingForm.submit();
                }
            }, 1000);
        }
        
        // 超时倒计时
        function startTimeoutCountdown() {
            let seconds = 5;
            timeoutCountdown.textContent = seconds;
            
            timeoutCountdownTimer = setInterval(function() {
                seconds--;
                timeoutCountdown.textContent = seconds;
                
                if (seconds <= 0) {
                    clearInterval(timeoutCountdownTimer);
                    // 停止摄像头并返回仪表盘
                    stopCamera();
                    window.location.href = '{{ url_for("user_dashboard") }}';
                }
            }, 1000);
        }
        
        // 停车场选择变化时隐藏提示
        parkingLotSelect.addEventListener('change', function() {
            parkingLotAlert.style.display = 'none';
        });
    });
</script>
{% endblock %} 